package com.sean.gulimall.authserver.controller;

import com.sean.gulimall.authserver.feign.ThridPartyFeignService;
import com.sean.gulimall.authserver.vo.UserRegisterVo;
import com.sean.gulimall.common.constant.AuthServerConstant;
import com.sean.gulimall.common.exception.BizCodeEnum;
import com.sean.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author 59244
 * @date 2022/1/28 19:23
 */
@Controller
public class LoginController {

    @Autowired
    ThridPartyFeignService thridPartyFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendcode(@RequestParam("phone") String phone){

        //TODO 1.接口防刷  60s内不能重复访问
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            String time = redisCode.split("_")[1];
            if(System.currentTimeMillis() - Long.parseLong(time) < 60000){
                return R.error(BizCodeEnum.SMS_MORE_EXCEPTION.getCode(),BizCodeEnum.SMS_MORE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0,5);

        //2.缓存验证码  长时间内有效  key- prefix+phone; value-code+time
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                code+"_"+System.currentTimeMillis(), 10, TimeUnit.MINUTES);

        thridPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    @PostMapping("/register")
    public String redister(@Valid UserRegisterVo vo, BindingResult result){

        if(result.hasErrors()){
            return "forward:/reg.html";
        }

        //注册成功，回到登录页
        return "redirect:/login.html";
    }
}
